import { defineStore } from 'pinia';
import axios from 'axios';
import { TOKEN_NAME } from '@/config/global';
import { store, usePermissionStore } from '@/store';

const InitUserInfo = {
  name: '',
  roles: [],
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '', // 默认token不走权限
    loginToken: '', // 仅用于登录token
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: {
    async login(userInfo: Record<string, unknown>) {
      const mockLogin = async (userInfo: Record<string, unknown>) => {
        try {
          const response = await axios.post('http://120.238.187.216:40006/transfer-api/api/user/login/', userInfo, {
            headers: { 'Content-Type': 'application/json;charset=UTF-8' },
          });
          // HTTP 状态码为 2xx，继续处理业务逻辑
          const res = {
            code: response.data.code, // 使用后端返回的业务状态码（如 data.code）
            data: response.data?.data?.token,
            message: response.data.msg,
          };

          if (res.code === 2000) {
            this.loginToken = res.data;
            this.token = import.meta.env.VITE_DIFY_API_KEY;
            this.userInfo = response.data?.data?.user; // 直接使用接口返回的user对象
            return res;
          }

          throw new Error(res.message || '业务逻辑错误'); // 抛出业务错误
        } catch (error) {
          let errorMessage = '登录失败，请检查网络连接';
          if (axios.isAxiosError(error)) {
            // 处理 HTTP 错误（4xx/5xx）或网络错误
            errorMessage = error.response?.data?.msg || error.message;
          } else if (error instanceof Error) {
            // 处理业务逻辑错误
            errorMessage = error.message;
          }
          throw new Error(errorMessage);
        }
      };

      const res = await mockLogin(userInfo);
      console.log(res);
    },
    async getUserInfo() {
      console.log('getUserInfo', this.userInfo);
      const mockRemoteUserInfo = async (token: string, userInfo: { username: any }) => {
        if (userInfo.username === 'admin') {
          return {
            // name: 'td_main',
            name: 'admin',
            roles: ['all'],
          };
        }
        return {
          // name: 'td_dev',
          name: userInfo.username,
          roles: ['UserIndex', 'ChatBase', 'login', 'ChatMessages'],
          // roles: ['all'],
        };
      };

      const res = await mockRemoteUserInfo(this.token, this.userInfo);

      this.userInfo = res;
    },
    async logout() {
      try {
        const response = await axios.post('http://120.238.187.216:40006/transfer-api/api/user/logout', this.loginToken);
        const res = {
          code: response.data.code, // 使用后端返回的业务状态码（如 data.code）
          data: response.data.data.token,
          message: response.data.msg,
        };
        if (res.code !== 2000) {
          throw res.message || '登出失败';
        }
        localStorage.removeItem(TOKEN_NAME);
        this.token = '';
        this.loginToken = '';
        this.userInfo = { ...InitUserInfo };
      } catch (e) {
        console.log(e);
      }
    },
    async removeToken() {
      this.token = '';
    },
  },
  persist: {
    afterRestore: (ctx) => {
      if (ctx.store.roles && ctx.store.roles.length > 0) {
        const permissionStore = usePermissionStore();
        permissionStore.initRoutes(ctx.store.roles);
      }
    },
  },
});

export function getUserStore() {
  return useUserStore(store);
}
